﻿using Microsoft.Build.Construction;
using Microsoft.Build.Evaluation;
using OD.ProjectCustomizationTool.Helpers;
using OD.ToolBox.IO;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;

namespace OD.ProjectCustomizationTool.Tools
{
    internal sealed class StyleCopRegister : ProjectUpdaterFromQualityFileBase, IFlatFileUpdate
    {
        protected override string QualityFileName
        {
            get { return Properties.Resources.StyleCopMsBuildTargetsFileName; }
        }

        protected override void InternalCreateQualityFile()
        {
            this.CopyFile(this.ResourceQualityFileFullPath, this.QualityFileFullPath);
            this.CopyFile(
                PathHelper.BuildFullPathToResource(Properties.Resources.StyleCopDllFileName),
                Path.Combine(this.DepositFullPath, Properties.Resources.StyleCopDllFileName));
        }

        /// <summary>
        /// <see cref="monitor_OnSaved"/>
        /// </summary>
        protected override void InternalUpdate()
        {
            // Deactivate the Style Cop on test projects.
            var value = !this.ProjectTypes.Contains(EProjectType.Test);
            this.SetProjectProperty(Properties.Resources.StyleCopEnabledProjectProperty, value.ToString());
        }

        void IFlatFileUpdate.Update()
        {
            var value = "  <Import Project=\"" + this.RelativePathToQualityFile + "\" />";
            var content = File.ReadAllLines(this.FullPathToProj).ToList();
            if (content.FirstOrDefault(x => String.Equals(x, value)) == null)
            {
                this.Monitor.Logger.WriteLine("Adding import '" + this.RelativePathToQualityFile + "'");
                var index = content.FindLastIndex(x => x.Contains("Microsoft.CSharp.targets"));
                content.Insert(index <= 0 ? content.Count() - 1 : index + 1, value);
                File.WriteAllLines(this.FullPathToProj, content);
            }
        }
    }
}
